package com.qujia.station.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.qujia.common.core.domain.model.LoginUser;
import com.qujia.common.exception.BaseException;
import com.qujia.common.exception.CustomException;
import com.qujia.common.utils.DateUtils;
import com.qujia.common.utils.SecurityUtils;
import com.qujia.common.utils.StringUtils;
import com.qujia.station.domain.*;
import com.qujia.station.domain.dto.CommodityTemplate;
import com.qujia.station.domain.vo.CommodityExportErrorVo;
import com.qujia.station.enums.MarketActivityType;
import com.qujia.station.mapper.CommodityMapper;
import com.qujia.station.mapper.NonOilCategoryMapper;
import com.qujia.station.service.*;
import com.qujia.station.utils.CodeUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * (Commodity)表服务实现类
 *
 * @author makejava
 * @since 2023-08-15 14:11:35
 */
@Service("commodityService")
@Slf4j
public class CommodityServiceImpl extends ServiceImpl<CommodityMapper,Commodity> implements CommodityService {
    @Resource
    private CommodityMapper commodityMapper;

    @Autowired
    private INonOilCategoryService nonOilCategoryService;

    @Autowired
    private SupplierService supplierService;

    @Autowired
    private MarketActivityService marketActivityService;

    @Autowired
    private ActivityCommodityRulesService activityCommodityRulesService;

    @Autowired
    private IStationService stationService;

    @Autowired
    private IEnterpriseService enterpriseService;

    @Autowired
    private NonOilCategoryMapper nonOilCategoryMapper;

    /**
     * 通过ID查询单条数据
     *
     * @param commodityId 主键
     * @return 实例对象
     */
    @Override
    public Commodity queryById(Long commodityId) {
        return commodityMapper.queryById(commodityId);
    }

    /**
     * 分页查询
     *
     * @param commodity 筛选条件
     * @param pageRequest      分页对象
     * @return 查询结果
     */
    @Override
    public Page<Commodity> queryByPage(Commodity commodity, PageRequest pageRequest) {
        long total = this.commodityMapper.count(commodity);
        return new PageImpl<>(this.commodityMapper.queryAllByLimit(commodity, pageRequest), pageRequest, total);
    }

    /**
     * 新增数据
     *
     * @param commodity 实例对象
     * @return 实例对象
     */
    @Override
    public Commodity insert(Commodity commodity) {
        LoginUser currentUser = SecurityUtils.getLoginUser();
        commodity.setCreateUser(currentUser.getUser().getUserId());
        commodity.setCreateTime(new Date());
        commodityMapper.insert(commodity);
        return commodity;
    }

    @Override
    public void insertCommodity(List<Commodity> commodityList) {
        // 参数校验
        for (Commodity commodity : commodityList) {
            Commodity newCommodity = new Commodity();
            newCommodity.setStationId(commodity.getStationId());
            newCommodity.setBarCode(commodity.getBarCode());
            Commodity com = commodityMapper.selectCommodity(newCommodity);
            if(Objects.nonNull(com)){
                throw new CustomException("商品已存在");
            }
            if(Objects.nonNull(commodity.getSupplierId())){
                Supplier supplier = new Supplier();
                supplier.setSupplierId(commodity.getSupplierId());
                Supplier result = supplierService.selectOneSupplier(supplier);
                if(Objects.nonNull(result)){
                    commodity.setSupplierName(result.getSupplierName());
                }
            }
        }
        for (Commodity commodity : commodityList) {
            synchronized (this) {
                String code = CodeUtil.createCode();
                commodity.setCommodityCode(code);
                commodity.setUpdateTime(new Date());
                insert(commodity);
            }
        }
    }

    /**
     * 修改数据
     *
     * @param commodity 实例对象
     * @return 实例对象
     */
    @Override
    public int update(Commodity commodity) {
        LoginUser currentUser = SecurityUtils.getLoginUser();
        commodity.setUpdateTime(new Date());
        commodity.setUpdateUser(currentUser.getUser().getUserId());
        if(StringUtils.isNotEmpty(commodity.getBarCode())) {
            Commodity com = new Commodity();
            com.setStationId(commodity.getStationId());
            com.setBarCode(commodity.getBarCode());
            Commodity result = commodityMapper.selectCommodity(com);
            if(Objects.nonNull(result) && !result.getCommodityId().equals(commodity.getCommodityId())){
                throw new BaseException("商品条形码已存在，不能修改条形码");
            }
        }
        if(Objects.nonNull(commodity.getEnterpriseId())){
            Enterprise enterprise = enterpriseService.selectEnterpriseById(commodity.getEnterpriseId());
            commodity.setEnterpriseName(Objects.nonNull(enterprise) ? enterprise.getEnterpriseName() : commodity.getEnterpriseName());
        }

        if(Objects.nonNull(commodity.getStationId())){
            Station station = stationService.selectStationById(commodity.getStationId());
            commodity.setStationName(Objects.nonNull(station) ? station.getStationName() : commodity.getStationName());
        }

        if(Objects.nonNull(commodity.getSupplierId())){
            Supplier req = new Supplier();
            req.setSupplierId(commodity.getSupplierId());
            Supplier supplier = supplierService.selectOneSupplier(req);
            commodity.setSupplierName(Objects.nonNull(supplier) ? supplier.getSupplierName() : commodity.getSupplierName());
        }

        return commodityMapper.update(commodity);
    }

    /**
     * 通过主键删除数据
     *
     * @param commodityId 主键
     * @return 是否成功
     */
    @Override
    public boolean deleteById(Long commodityId) {
        return commodityMapper.deleteById(commodityId) > 0;
    }

    @Override
    public int delete(List<Long> ids) {
        if(ids!=null&&ids.size()>0){
            return commodityMapper.deleteByIds(ids);
        }
        return 0;
    }

    @Override
    public List<Commodity> query(Commodity commodity) {
        Long categoryId = commodity.getCategoryId();
        if(categoryId!=null){
            List<Long> childIds = nonOilCategoryService.getChildIds(categoryId);
            childIds.add(categoryId);
            commodity.setCategoryIds(childIds);
        }
        PageHelper.startPage(commodity.getPageNum(), commodity.getPageSize(), commodity.getOrderBy());
        List<Commodity> querys = commodityMapper.query(commodity);
        PageHelper.clearPage();
        if(CollectionUtils.isEmpty(querys)){
            return querys;
        }
        for (Commodity query : querys) {
            if(Objects.nonNull(query.getCategoryId())) {
                NonOilCategory nonOilCategory = nonOilCategoryService.queryById(query.getCategoryId());
                if (Objects.nonNull(nonOilCategory)) {
                    query.setCategoryName(nonOilCategory.getCategoryName());
                }
            }
//            if(Objects.nonNull(query.getSupplierId())) {
//                Supplier req = new Supplier();
//                req.setSupplierId(query.getSupplierId());
//                log.info("商品列表查询供应商：[{}]", JSONObject.toJSONString(req));
//                Supplier supplier = supplierService.selectOneSupplier(req);
//                if (Objects.nonNull(supplier)) {
//                    query.setSupplierName(supplier.getSupplierName());
//                }
//            }
        }
        return querys;
    }

    @Override
    public List<Commodity> selectCommodityList(Commodity commodity) {
        List<Commodity> commodityList = commodityMapper.selectCommodityList(commodity);
        for (Commodity com : commodityList) {
            NonOilCategory nonOilCategory = nonOilCategoryService.queryById(com.getCategoryId());
            if(Objects.nonNull(nonOilCategory)) {
                com.setCategoryName(nonOilCategory.getCategoryName());
            }
        }
        return commodityList;
    }

    @Override
    public Commodity queryCommodity(Commodity commodity) {
        Commodity com = commodityMapper.selectCommodity(commodity);
        if(Objects.nonNull(com) && Objects.nonNull(com.getCategoryId())) {
            NonOilCategory nonOilCategory = nonOilCategoryService.queryById(com.getCategoryId());
            if (Objects.nonNull(nonOilCategory)) {
                com.setCategoryName(nonOilCategory.getCategoryName());
            }
        }
        return com;
    }

    @Override
    public Commodity externalQueryCommodity(Commodity commodity) {
        Commodity com = commodityMapper.selectCommodity(commodity);
        if(Objects.isNull(com)){
            throw new BaseException("商品不存在");
        }
        NonOilCategory nonOilCategory = nonOilCategoryService.queryById(com.getCategoryId());
        if(Objects.nonNull(nonOilCategory)) {
            com.setCategoryName(nonOilCategory.getCategoryName());
        }
        // 计算商品优惠价格
        calculateDiscountPrice(com);
        return com;
    }

    // 计算商品优惠价格
    private void calculateDiscountPrice(Commodity commodity){
        // 获取当前门店的活动
        List<MarketActivity> marketActivities = marketActivityService.progressMarketActivityList(commodity);
        if(CollectionUtils.isEmpty(marketActivities)){
            commodity.setDiscountPrice(commodity.getSalePrice());
            return;
        }

        // 更具活动和商品 匹配优惠规则
        ActivityCommodityRules rules = activityCommodityRulesService.selectCommodityDiscount(commodity, marketActivities);
        if(Objects.isNull(rules) || Objects.isNull(rules.getCommodityId())){
            commodity.setDiscountPrice(commodity.getSalePrice());
            return;
        }
        // 计算优惠价格
        if(MarketActivityType.DISCOUNT_NUM.getValue().equals(rules.getMarketActivityType())){
            // 打折 计算商品优惠价格 四舍五入 保留2位小数
            BigDecimal discountPrice = commodity.getSalePrice().subtract(commodity.getSalePrice()
                    .multiply(BigDecimal.valueOf(rules.getDiscountNum()/100))
                    .setScale(2, RoundingMode.HALF_UP));
            commodity.setDiscountPrice(discountPrice);
        }
        if(MarketActivityType.SPECIAL_PRICE.getValue().equals(rules.getMarketActivityType())){
            // 特价 计算商品优惠价格
            commodity.setDiscountPrice(rules.getSpecialPrice());
        }
    }

    @Override
    public List<Long> getSupplierIdList(Commodity commodity) {
        return commodityMapper.getSupplierIdList(commodity);
    }

    @Override
    public List<CommodityExportErrorVo> exportAddWarehouseList(List<CommodityTemplate> commodityTemplateList) {
        return checkCommodityExports(commodityTemplateList);
    }

    // 校验批量导入商品
    private List<CommodityExportErrorVo> checkCommodityExports(List<CommodityTemplate> commodityTemplateList){
        List<CommodityExportErrorVo> commodityExportErrorVoList = new ArrayList<>();
        int num = 1;
        List<Commodity> commodities = new ArrayList<>();
        for (CommodityTemplate commodityTemplate : commodityTemplateList) {
            if(Objects.isNull(commodityTemplate)){
                CommodityExportErrorVo commodityExportErrorVo = new CommodityExportErrorVo();
                commodityExportErrorVo.setNum(num);
                commodityExportErrorVo.setReason("整行数据不存在");
                commodityExportErrorVoList.add(commodityExportErrorVo);
                num++;
                continue;
            }
            String reason = "";
            if(Objects.isNull(commodityTemplate.getStationId())){
                reason = reason + "油站id不为空,";
            }

            if(StringUtils.isEmpty(commodityTemplate.getCommodityName())){
                reason = reason + "商品名称不为空,";
            }
            Commodity query = new Commodity();
            Station station = stationService.selectStationById(commodityTemplate.getStationId());
            if(Objects.isNull(station)){
                reason = reason + "油站不存在,";
            }else if(-1L == station.getEnterpriseId()) {
                query.setEnterpriseId(-1L);
                query.setEnterpriseName("-");
            }else {
                Enterprise enterprise = enterpriseService.selectEnterpriseById(station.getEnterpriseId());
                if(Objects.nonNull(enterprise)){
                    query.setEnterpriseId(enterprise.getEnterpriseId());
                    query.setEnterpriseName(enterprise.getEnterpriseName());
                }
            }
            if(StringUtils.isNotEmpty(commodityTemplate.getBarCode())){
                Commodity com = new Commodity();
                com.setStationId(commodityTemplate.getStationId());
                com.setBarCode(commodityTemplate.getBarCode());
                Commodity commodity = commodityMapper.selectCommodity(com);
                if(Objects.nonNull(commodity)){
                    reason = reason + "商品已存在,";
                }
            }
            NonOilCategory category = new NonOilCategory();
            if(StringUtils.isNotEmpty(commodityTemplate.getCategoryCode())){
                category = nonOilCategoryMapper.selectByCategoryCode(commodityTemplate.getCategoryCode());
                if(Objects.isNull(category)){
                    reason = reason + "分类不存在,";
                }
            }

            if(reason.length() >0){
                CommodityExportErrorVo commodityExportErrorVo = new CommodityExportErrorVo();
                commodityExportErrorVo.setNum(num);
                commodityExportErrorVo.setReason(reason);
                commodityExportErrorVo.setStationId(commodityTemplate.getStationId());
                commodityExportErrorVo.setCommodityName(commodityTemplate.getCommodityName());
                commodityExportErrorVoList.add(commodityExportErrorVo);
            } else {
                query.setStationId(commodityTemplate.getStationId());
                query.setStationName(station.getStationName());
                query.setBarCode(commodityTemplate.getBarCode());
                query.setCategoryId(category.getCategoryId());
                query.setCategoryName(category.getCategoryName());
                query.setSupplierName(commodityTemplate.getSupplierName());
                query.setCommodityName(commodityTemplate.getCommodityName());
                query.setRetailPrice(commodityTemplate.getRetailPrice());
                query.setSalePrice(commodityTemplate.getSalePrice());
                query.setUnit(commodityTemplate.getUnit());
                commodities.add(query);
            }
            num++;
        }
        if(CollectionUtils.isNotEmpty(commodities)){
            // 入库
            insertCommodity(commodities);
        }
        return commodityExportErrorVoList;
    }


    @Override
    public List<Commodity> selectAllCommodityList(Commodity commodity) {
        return commodityMapper.selectAllCommodityList(commodity);
    }
}
